//
//  CZOauthController.swift
//  SinaWeibo
//
//  Created by 浩记 on 16/3/21.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
class CZOauthController: UIViewController {

    override func loadView() {
        //在这里设置控制器的view为webView的好处是后面需要添加约束,自己会和屏幕一样大
        view = webView
        
        //设置webView 的代理，就有加载完webView的回调方法
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //背景颜色
        view.backgroundColor = UIColor.whiteColor()
        
        //设置导航栏
        setUpNavigation()
        
        //创建请求,拥有授权url的请求
        let request = NSURLRequest(URL: CZNetWorkTools.sharedInstance.oAuthURL())
        
        //加载webView页面的请求
        webView.loadRequest(request)
        
        // 弹出正在加载的提示
        // showWithStatus,需要主动关闭
        SVProgressHUD.showWithStatus("正在加载中..", maskType: SVProgressHUDMaskType.Black)
        // showInfoWithStatus,会自动关闭
        //        SVProgressHUD.showInfoWithStatus("正在加载", maskType: SVProgressHUDMaskType.Clear)
        //        SVProgressHUD.showErrorWithStatus("正在加载")
    }

    func setUpNavigation(){
        //导航栏标题
        title = "新浪微博"
        //左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "didClickLeftBarButtonItem")
        //右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "didClickRightBarButtonItem")
    }

    //MARK:- 点击导航栏按钮事件
    //左按钮
    func didClickLeftBarButtonItem(){
        // js代码的字符串
        let jsCode = "document.getElementById('userId').value='503715677@qq.com';document.getElementById('passwd').value='zhouhao168'"
        
        // 执行js代码
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
        
    }
    //右按钮
    func didClickRightBarButtonItem(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK:- 懒加载
    ///webView
     private var webView : UIWebView = UIWebView()
}

// MARK: - 扩展 CZOauthViewController 实现 UIWebViewDelegate
extension  CZOauthController: UIWebViewDelegate {
    ///加载开始
    func webViewDidStartLoad(webView: UIWebView) {
//        SVProgressHUD.show()
    }
    
    //加载请求完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()//关闭提示
    }
    
    //是否加载某个url，，返回true表示加载，false表示不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 点击取消: "http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330"
        
        // 点击授权: "http://www.baidu.com/?code=e67b175d1dff25aa630f0b1b74daa3f5"
        let urlString = request.URL!.absoluteString
//        print("urlString －－\(urlString)")
        // 当点击了取消后授权后都会加载授权回调地址,所以判断如果是授权回调地址就表示点击的是 取消 或 授权
        // 不是授权回调地址,让他加载
        if !urlString.hasPrefix(redirect_uri){
            return true
        }else{
            //加载的授权回调地址，说明点击是取消或者授权
            //获取参数
            let query = request.URL?.query//get请求？后的参数
            //判断query是否以code=开头，如果是的话点击的就是授权，不是的话点击的就是取消
            let codeString = "code="
            if query!.hasPrefix(codeString){//点击授权
                //code=e67b175d1dff25aa630f0b1b74daa3f5
                //截取code=后面的，作为网络请求授权令牌数据的参数
                let nsquery = query! as NSString //转换成oc字符串来截取
                let code = nsquery.substringFromIndex(codeString.characters.count)//截取
                print("code \(code)")
               //TODO: 1创建账户模型，保存属性，2,VM模型保存数据到沙盒（归档和解档）3，获取授权AccessToken通知控制器，没有错误就关闭授权页面，回到主页，错误就提示获取授权令牌失败，4，欢迎界面，5,新特性界面

            }else{//点击取消
                didClickRightBarButtonItem()
            }
            
            
            
            
        return false
        }
    }
    
}